package com.sbck.cs3;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.sbck.cs3.MyClass.DeviceLog;
import com.sbck.cs3.MyClass.MessageType;
import com.sbck.cs3.MyClass.MyMessage;
import com.sbck.cs3.MyClass.MyOpenHelper;
import com.sbck.cs3.MyClass.SocketUtil;
import com.sbck.cs3.MyClass.TChState;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import com.sbck.cs3.fragment.DeviceInfoFragment;
import com.sbck.cs3.fragment.DeviceLogFragment;
import com.sbck.cs3.fragment.DeviceRealtimeInfomationFragment;
import com.sbck.cs3.fragment.FireFragment;
import com.sbck.cs3.fragment.MapFragment;
import com.sbck.cs3.fragment.UserCtrlFragment;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private MyOpenHelper openHelper;
    private UserCtrlFragment userCtrlFragment;
    private DeviceRealtimeInfomationFragment deviceRealtimeInfomationFragment;
    private DeviceLogFragment deviceLogFragment;
    private FireFragment fireFragment;
    private DeviceInfoFragment deviceInfoFragment;
    private MapFragment mapFragment;

    private Button buttonHeart;
    private Button buttonFire;
    private Button buttonParameters;
    private Button buttonUserCtrl;
    private Button buttonLog;
    private Button buttonDevice;

    private Button buttonMap;
    public SocketUtil cSocketUtil;
    private Button buttonNetConnect;
    private TextView textViewNetConnect;
    private TextView textViewHeartCount;
    private Handler handler = new Handler(); //EventBus
    @SuppressLint({"MissingInflatedId", "SetTextI18n"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userCtrlFragment = new UserCtrlFragment();

        getFragmentManager().beginTransaction().replace(R.id.fl_container,userCtrlFragment).commit();

        deviceLogFragment = new DeviceLogFragment();
        deviceRealtimeInfomationFragment = new DeviceRealtimeInfomationFragment();
        fireFragment = new FireFragment();
        deviceInfoFragment = new DeviceInfoFragment();
        mapFragment = new MapFragment();


        //EventBus
        if(!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }

        openHelper = new MyOpenHelper(this);

        buttonHeart = findViewById(R.id.Btn_MainActivity_Heart);
        buttonParameters =  findViewById(R.id.Btn_MainActivity_Parameters);
        buttonUserCtrl = findViewById(R.id.Btn_MainActivity_AutoCtrl);
        buttonFire = findViewById(R.id.Btn_MainActivity_Fire);
        buttonLog = findViewById(R.id.Btn_MainActivity_Log);
        buttonDevice = findViewById(R.id.Btn_MainActivity_Device);
        buttonMap = findViewById(R.id.Btn_MainActivity_Map);

        buttonNetConnect = findViewById(R.id.Btn_MainActivity_NetConnect);
        textViewNetConnect = findViewById(R.id.TV_MainActivity_NetConnect);
        textViewHeartCount = findViewById(R.id.TV_MainActivity_HeartCount);

        buttonNetConnect = findViewById(R.id.Btn_MainActivity_NetConnect);
        textViewNetConnect = findViewById(R.id.TV_MainActivity_NetConnect);
        textViewHeartCount = findViewById(R.id.TV_MainActivity_HeartCount);

        InitButton();

        if(MyGlobal.IsFirstRun)
        {
            InitGlobalVar();
            MyGlobal.IsFirstRun = false;
            MyGlobal.IsPopToast.set(true);
        }

        MyGlobal.HeartCount = 0;
        cSocketUtil = new SocketUtil();
        cSocketUtil.startClient();
        MyGlobal.socketUtil = cSocketUtil;

        buttonHeart.setVisibility((View.GONE));


        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        String str ;
        if(Boolean.TRUE.equals(MyGlobal.setting.IsWifi.get()))
            str = "WIFI模式 - ";
        else
            str = "公网模式 - ";

        if(MyGlobal.IsNetConnected)
        {
            textViewNetConnect.setText(str+"已连接 等待心跳");
            textViewNetConnect.setTextColor(Color.GREEN);
            buttonNetConnect.setBackgroundColor(Color.YELLOW);
        }
        else
        {
            textViewNetConnect.setText(str+"未连接");
            textViewNetConnect.setTextColor(Color.RED);
        }

        //跳转主界面
        if(Boolean.TRUE.equals(MyGlobal.unitinfo.IsNew.get()))
        {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,deviceInfoFragment).commit();
        }
        else {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,userCtrlFragment).commit();

        }
    }

    private void InitGlobalVar()
    {
        //启动数据接收线程
        MyGlobal.unitstatus = new UNITSTATUS();
        MyGlobal.heartDataArrayList = new ArrayList<>();


        //初始化焰条数组
        MyGlobal.tChStateArrayList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            TChState t = new TChState(i+1);
            MyGlobal.tChStateArrayList.add(t);
        }

        //初始化日志
        MyGlobal.deviceLogArrayList = new ArrayList<>();
        DeviceLog deviceLog = new DeviceLog("启动", Color.BLACK);
        MyGlobal.deviceLogArrayList.add(deviceLog);

    }

    private void ClearButtonColor()
    {
        buttonHeart.setVisibility((View.GONE));
        buttonUserCtrl.setBackgroundColor(Color.parseColor("#6750A4"));
        buttonFire.setBackgroundColor(Color.parseColor("#6750A4"));
        buttonLog.setBackgroundColor(Color.parseColor("#6750A4"));
        buttonParameters.setBackgroundColor(Color.parseColor("#6750A4"));
        buttonMap.setBackgroundColor(Color.parseColor("#6750A4"));
        buttonDevice.setBackgroundColor(Color.parseColor("#6750A4"));
    }
    private void InitButton()
    {
        buttonHeart.setOnClickListener(view -> {
            MyGlobal.socketUtil.GetHeart();
        });
        //buttonUserCtrl 自动控制
        buttonUserCtrl.setOnClickListener(view -> {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,userCtrlFragment).commitNowAllowingStateLoss();
            ClearButtonColor();
            buttonUserCtrl.setBackgroundColor(Color.parseColor("#9400D3"));
        });
        //buttonParameters 心跳数据界面按钮
        buttonParameters.setOnClickListener(view -> {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,deviceRealtimeInfomationFragment).commitNowAllowingStateLoss();
            ClearButtonColor();
            buttonHeart.setVisibility((View.VISIBLE));
            buttonParameters.setBackgroundColor(Color.parseColor("#9400D3"));
        });

        // 焰条 按钮
        buttonFire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager().beginTransaction().replace(R.id.fl_container, fireFragment).commitNowAllowingStateLoss();
                ClearButtonColor();
                buttonFire.setBackgroundColor(Color.parseColor("#9400D3"));
            }
        });

        //buttonLog 消息按钮
        buttonLog.setOnClickListener(view -> {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,deviceLogFragment).commitNowAllowingStateLoss();
            ClearButtonColor();
            buttonLog.setBackgroundColor(Color.parseColor("#9400D3"));
        });


        // 设备信息界面按钮
        buttonDevice.setOnClickListener(view -> {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,deviceInfoFragment).commitNowAllowingStateLoss();
            ClearButtonColor();
            buttonDevice.setBackgroundColor(Color.parseColor("#9400D3"));
        });
        //buttonMap 地图按钮
        buttonMap.setOnClickListener(view -> {
            getFragmentManager().beginTransaction().replace(R.id.fl_container,mapFragment).commitNowAllowingStateLoss();
            ClearButtonColor();
            buttonMap.setBackgroundColor(Color.parseColor("#9400D3"));
        });

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().unregister(this);
        }
        MyGlobal.socketUtil.Close();

    }
    private void ShowToast(String msg)
    {
        if(Boolean.TRUE.equals(MyGlobal.IsPopToast.get()))
            Toast.makeText(this,msg , Toast.LENGTH_SHORT).show();
    }
    //事件总线
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MyMessage myMessage) {

        switch (myMessage.messageCategory) {
            case SocketReceive:
                buttonNetConnect.setBackgroundColor(Color.GREEN);
                handler.postDelayed(runnable,500);
                if(myMessage.messageType == MessageType.Heart)
                {
                    String str;
                    if (Boolean.TRUE.equals(MyGlobal.setting.IsWifi.get()))
                        str = "WIFI模式 - ";
                    else
                        str = "4G公网模式 - ";
                    textViewNetConnect.setText(str + "已连接");
                    textViewHeartCount.setText(String.valueOf(MyGlobal.HeartCount));
                }
                else
                {
                    String msg = "收到: [" + myMessage.messageType.getName() + "] 命令回复";
                    ShowToast(msg);
                }
                break;
            case SocketSend:
                buttonNetConnect.setBackgroundColor(Color.BLUE);
                break;
            case SocketError:
                break;
        }
    }
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            buttonNetConnect.setBackgroundColor(Color.parseColor("#006400"));
        };
    };
}